import requests
import os
from bs4 import BeautifulSoup
import asyncio
import aiohttp
import aiofiles
from Crypto.Cipher import AES

'''
思路：
    1.拿到主页面的页面源代码，找到iframe
    2.从iframe的页面源代码中拿到m3u8文件的地址
    3.下载第一层m3u8文件 ——> 下载第二层m3u8文件（视频存放路径）
    4.下载视频
    5.下载秘钥，进行解密操作
    6.合并所有的ts文件作为一个mp4文件
'''


def get_iframe_src(url):
    # respon = requests.get(url)
    # main_page = BeautifulSoup(respon.text,'html.parser')
    # src = main_page.find('iframe').get('src')
    # return src
    return 'https://www.1717yun.com/jx/ty.php?url=http://v.qq.com/x/cover/639agzdh10yu2q2/v0026oj49rc.html'  # 测试用

async def download_ts(url,name,session):
    async with session.get(url) as resp:
        async with aiofiles.open(f'video_s/{name}','wb') as f:
            await f.write(await resp.content.read())  # 把下载内容写到文件中
    print(f"{name}下载完毕!")

async def aio_download(up_url):
    tasks = []
    async with aiohttp.ClientSession() as session:
        async with aiofiles.open('xxx.txt','w',encoding='utf-8') as f:
            async for line in f:
                if line.startswith('#'):
                    continue
                line = line.strip()  # 去掉没用的空格和换行符
                # 拼接真正的ts路径
                ts_url = up_url + line
                task = asyncio.create_task(download_ts(ts_url,line,session))  # 创建任务
                tasks.append(task)

            await asyncio.wait(tasks)   # 等待任务结束

def get_key(url):
    resp = requests.get(url)
    return resp.text

async def dec_ts(name,key):
    aes = AES.new(key=key,IV=b'0000000000000000',mode=AES.MODE_CBC)   # key多长IV放多长
    async with aiofiles.open(f'data/video/video_s/{name}','rb') as f1,\
        aiofiles.open(f"data/video/video_s/temp_{name}",'wb') as f2:

        bs = await f1.read()   # 从保存到的ts文件里读取到内容
        await f2.write(aes.decrypt(bs)) # 把解密好的内容写入文件
    print(f"{name}处理完毕!")

async def aio_dec(key):
    # 解密
    tasks = []
    async with aiofiles.open('下载下来的ts结尾的m3u8文件','r',encoding='utf-8') as f:
        async for line in f:
            if line.startswith("#"):
                continue
            line = line.strip()
            # 开始创建异步任务
            task = asyncio.create_task(dec_ts(line,key))
            tasks.append(task)

        await asyncio.wait(tasks)

def merge_ts():
    # mac: cat 1.ts 2.ts 3.ts > xxx.mp4
    # windows: copy /b 1.ts+2.ts+3.ts xxx.mp4
    lst = []
    with open("下载下来的ts结尾的m3u8文件",'r',encoding='utf-8') as f:
        for line in f:
            if line.startswith("#"):
                continue
            line = line.strip()
            lst.append(f"data/video/video_s/temp_{line}")

    s = "+".join(lst)
    os.system(f"cat /b {s} data/video/video_s/xxx.mp4")
    print('搞定!')


def main(url):
    # 1、拿到主页面的页面源代码，找到iframe对应的url
    iframe_src = get_iframe_src(url)

    second_m3u8_url_up = ''

    # 拿到秘钥
    key_url = second_m3u8_url_up + "key.key"  # 正常应该从文件里获取 可用正则
    key = get_key(key_url)

    # 解密
    asyncio.run(aio_dec(key))

    # 合并ts文件为mp4文件
    merge_ts()

if __name__ == '__main__':
    url = 'https://www.91kanju.com/vod-play/326-2-1.html'
    main(url)
